// pages/map/orderAndDriverGoing/orderAndDriverGoing.js
const handler = require("../../../utils/function.js");
var api = require("../../../api.js"),
  QQMapWX = require("../../../utils/qqmap-wx.js"),
  app = getApp();
var demo = new QQMapWX({
  key: 'EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD' // 必填
});
Page({
    /**
     * 页面的初始数据
     */
    data: {
        //用户当前位置图标
      polyline: [{
        points: [],
        color: "#0299de",
        width: 9,
        dottedLine: false,
        arrowLine: true,
      },
      ],
      make: {},
        controls: [{
            id: 1,
            // iconPath: '../../../images/user/icon-22.png',
            // position: {
            //     left: 10,
            //     top: 10,
            //     width: 50,
            //     height: 50
            // },
            // clickable: true
        }], //人物图片定位
        address:{},
        startAddress: {},
        order_going_m: 0,
        order_going_s: 0,
        myShow: true, //显示my的页面
        zuoyou: "icon-zuoyou", //my
        avatar: "../../../images/user/icon-07.png",
        buttonText: "登录",
        username: "未登录",
        orderGoing: false,
        homeHandlerShow: true,
        phone: "",
        order_no: '',
        is_send: 0,
        left_width: 750,
        timeTaskHandler:"",//页面跳转时间定时器
        time:'',//页面等待时间定时器
        t:"00:01",
        get_order: wx.getStorageSync("get_order"),//获取订单数量
    },
  relstiveServerHandler:function(){
    handler.callPhoneHandler(wx.getStorageSync("serverphone"));
  },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            order_no: options.order_no,
        })
        //this.time()
      // 获取优惠券
      if (options.uid) {
        app.shareCouponsMessage(options.uid)
      }
    },
    regionchange(e) {
        // console.log("regionchange", e.type)
    },
    markertap(e) {
        // console.log("markertap", e.markerId)
    },
    // 地图图片点击事件
    controltap(e) {
        // console.log("map controltap", e.controlId)
        if (e.controlId === 1) {
          // this.openMyPageHandler();
          wx.navigateTo({
            url: '/pages/map/my/my',
          })
        } else {
            const addresses = handler.getLatLntHandler((res) => {
                //  console.log("一键定位",res);
                this.setData({
                    address: res, //开始位置
                })
            });
        }
    },
    timeTask: function() {
        let order_going_s = this.data.order_going_s;
        let order_going_m = this.data.order_going_m;
        let is_send = this.data.is_send;
        order_going_s++;
        if (order_going_s > 59) {
            order_going_s = 0;
            order_going_m++;
        }
        this.setData({
            order_going_s,
            order_going_m
        })
    },
    // deleteOrderHandler 取消订单事件
    deleteOrderHandler: function(e) {
        var that = this;
        wx.showModal({
          title: '提示',
          content: '确认要取消订单',
          success:function(res){
            if(res.confirm){
              app.request({
                url: api.order.cancel_order,
                method: 'post',
                data: {
                  formid:e,
                  order_no: that.data.order_no,
                },
                success: function (rs) {
                  if (rs.code == 1) {
                    wx.showToast({
                      title: '订单取消已成功',
                    })
                    clearInterval(this.timeTask)
                    wx.reLaunch({
                      url: '../driverServer/driverServer',
                    })
                    // handler.intoPageHandler('');
                  } else {
                    wx.showToast({
                      title: rs.msg,
                    })
                  }
                }
              })
            }
          }
        })
       
    },
    apply_refund:function(){
      console.log('申请退单')
      var that =this;
      app.request({
        url: api.order.apply_refund,
        method: 'post',
        data: {
          order_no: that.data.order_no,
        },
        success: function (rs) {
          console.log('申请退款结果',rs);
          if (rs.code == 1) {
            wx.showToast({
              title: '订单取消已成功',
            })
            clearInterval(this.timeTask)
            setTimeout(function(){
              wx.reLaunch({
                url: '../driverServer/driverServer',
              })
            },3000)
          } else {
            console.log('zcj')
            wx.showToast({
              title: rs.msg,
              icon:"none"
            })
          }
        }
      })
    },
    callphone:function(){
      console.log('呼叫平台')
      var t = this,phone = wx.getStorageSync('makephone');
      wx.makePhoneCall({
        phoneNumber: phone
      })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
  // 获取距离
  get_distance: function (start, target, callback) {
    demo.calculateDistance({
      from: {
        latitude: start.location.lat,
        longitude: start.location.lng
      },
      to: [{
        latitude: target.location.lat,
        longitude: target.location.lng
      }],
      success: function (res) {
        callback({ distance: res.result })
      },
      fail: function (res) {
        callback(res)
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  //路线规划以及距离计算
  get_line_and_count_distance() {
    let that = this;
    let start = this.data.startAddress;
    let end = this.data.endAddress;
    if (start && end) {
      // 获取位置路线
      this.getPolyline(start, end)
      // 计算距离
      // this.get_distance(start, end, res => {
      //   let km_num = (res.distance.elements[0].distance / 1000).toFixed(1)
        // 获取预计金额
      // if (!start&&!end){
      //   return
      // }
        // app.request({
        //   url: api.order_forecast.order_forecast,
        //   method: "post",
        //   data: {
        //     mileage: km_num
        //   },
        //   success(data) {
        //     console.log("order_forecast")
        //     console.log(data)
        //     that.setData({
        //       price: data.data.price
        //     })
        //   }

        // })
        // this.setData({ distance: km_num, is_distance: true });
      // })
    }
  },
  // 获取距离
  get_distance: function (start, target, callback) {
    demo.calculateDistance({
      from: {
        latitude: start.location.lat,
        longitude: start.location.lng
      },
      to: [{
        latitude: target.location.lat,
        longitude: target.location.lng
      }],
      success: function (res) {
        callback({ distance: res.result })
      },
      fail: function (res) {
        callback(res)
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  // 获取位置路线
  getPolyline: function (start, target) {
    let that = this;
    const { polyline } = this.data;
    console.log(start, target)
    // debugger
    // wx.setStorageSync("startAddress", { location: { lng: start.lng, lat: start.lat } });
    // wx.setStorageSync("endAddress", { location: { lng: target.lng, lat: target.lat } });
    const froms = start.location.lat + "," + start.location.lng + "&to=" + target.location.lat + "," + target.location.lng
    wx.request({
      url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${froms}&key=Z6RBZ-6H4CU-AV6V5-2OTIO-Q2CLZ-VMF5T`,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res);

        if (res.data.status != 384) {
          // 坐标解压
          var coors = res.data.result.routes[0].polyline;
          for (var i = 2; i < coors.length; i++) {
            coors[i] = coors[i - 2] + coors[i] / 1000000
          }
          console.log(coors);
          const points = [];
          // 转化为 坐标点数组
          for (var j = 0; j < coors.length; j += 2) {
            points[points.length] = {
              longitude: coors[j + 1],
              latitude: coors[j]
            }
          }
          polyline[0].points = points;
          console.log(polyline)

          that.setData({
            polyline
          });
        }
      },
      fail: function () {
        // showToast('网络出现错误', "none")
      }
    })
  },
  // 绘制图标
  mark_icon() {
    let that = this
    let start = this.data.startAddress;
    let end = this.data.endAddress;
    //添加图标
    let make = [];
    if (start) {
      make[0] = { id: 0, iconPath: "/images/user/icon-44.png", latitude: start.location.lat, longitude: start.location.lng, width: 40, height: 40 };

    }
    if (end) {
      make[1] = { id: 1, iconPath: "/images/user/icon-43.png", latitude: end.location.lat, longitude: end.location.lng, width: 40, height: 40 };

    }

    that.setData({
      make: make
    });
  },
  // 订单提示
  gotoNews: function () {
    wx.navigateTo({
      url: '/pages/user/news/news',
    })
  },
  goToMy:function(){
    wx.navigateTo({
      url:'/pages/map/my/my'
    })
  },
  goToHome:function(){
    wx.navigateTo({
      url:'/pages/map/driverServer/driverServer'
    })
  },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        var that = this;
       
        if (wx.getStorageSync("userMessage") !== "") {
            this.setData({
                avatar: wx.getStorageSync("userMessage").avatar,
                username: wx.getStorageSync("userMessage").username,
                buttonText: wx.getStorageSync("userMessage").buttonText,
                phone: wx.getStorageSync("phonep"),
            });
        }
        var time=this.data.time;
        that.postionTask();
        
        this.setData({time})
        handler.getLatLntHandler(res=>{
          // debugger
          that.setData({
            address: res,
            startAddress: res.startAddress, //开始位置
          })
        })
        this.changeIcon();
       this.gotomapi()
        // 订单提示
      if (wx.getStorageSync("get_order")) {
        this.setData({ get_order: wx.getStorageSync("get_order") })
      }
    },
    /*
     * 定时获取订单状态及代驾人员位置
     */
    postionTask: function() {
        let that = this;
        var is_send = that.data.is_send;
        app.request({
            url: api.order.waiting,
            method: 'post',
            data: {
                order_no: that.data.order_no,
            },
            success: function(rs) {
                if (rs.code == 1) {
                  
                  

                  // apart  总距离
                  // total_price 总价

                    that.setData({
                        is_send: rs.data.is_send,
                        startAddress: rs.data.lang,
                        endAddress: { location: rs.data.target_adds_location},
                        // t:t,
                        waiting_time: rs.data.waiting_time,
                        message: rs.data.message,
                        distance: rs.data.apart, 
                        price: rs.data.total_price,
                        is_distance: true
                    })
                    that.mark_icon();
                    that.get_line_and_count_distance()
                  that.add_time(rs.data.waiting_time)
                }
            }
        })
    },
    // 转换成时间
    change_time:function(e){
      var time = e;
      var min = Math.floor(time / 60) % 60; //分
      var sec = time % 60; //秒
      var t = ''
      // if (hour < 10) {
      //   t += '0' + hour + "时";
      // } else {
      //   t += hour + "时";
      // }
      if (min < 10) { t += "0"; }
      t += min + ":";
      //console.log(t, 'ttttttttt')
      if (sec < 10) { t += "0"; }
      t += sec //.toFixed(2);
      console.log(t,'132456789123456789')
      let waiting_time = this.data.waiting_time
      this.setData({ t: t, waiting_time: ++waiting_time})
    },
    gotomapi:function(){
      var that =this;
      app.request({
        url: api.order.driver_order,
        method: 'post',
        data: {
          order_no: that.data.order_no,
        },
        success: function (rs) {
          console.log(rs)
          if (rs) {
            wx.showToast({
              title: '司机已接单',
            })
            clearTimeout()
            setTimeout(function(){
              wx.navigateTo({
                url: '/pages/map/getOrderNotGoing/getOrderNotGoing?order_no='+that.data.order_no,
              })
            },3000)
          }else{
           setTimeout(function(){
              that.gotomapi()
           }, 10000);
          } 
        }
      })
    },
    // 时间自加
    add_time:function(e){
      let that=this;
     
      console.log(e,'22222222222222')
      var time = setInterval(() => {
        let t = that.data.t
        let waiting_time = this.data.waiting_time
        that.change_time(waiting_time)
      }, 1000);
      this.setData({ time: time})
    },
    // 修改用户和一键定位位置
    changeIcon: function() {
        const that = this;
        const {
            controls
        } = this.data;
        wx.getSystemInfo({
            success: function success(res) {
                var controlsH = res.windowWidth / 750 * 700; //计算一像素的宽度 res.windowWidth
                var map_height = res.windowHeight - controlsH;
				var map_width = res.windowWidth
                // console.log(res, '2222222222')
                controls[1] = {
                    id: 2,
                    iconPath: '../../../images/user/icon-30.png',
                    position: {
                        top: map_height - 56,
                        left: map_width - 50,
                        width: 40,
                        height: 40
                    },
                    clickable: true
                };
                that.setData({
                    winPath: {
                        w: res.windowWidth,
                        h: res.windowHeight
                    },
                    map_height,
                    controls,
                });
            }
        });
    },
  formSubmit:function(e){
    var user_id = wx.getStorageSync('user_info').id;
    var formid = e.detail.formId;
    console.log(formid, '22222222222222222');
    // if (formid) {
      this.deleteOrderHandler(formid)
    // }
  },
    //
  onHide(){
    var { timeTaskHandler, time } = this.data;
    clearInterval(timeTaskHandler)
    clearInterval(time)
  },
    //清除时间定时器
  onUnload(){
    var { timeTaskHandler,time}=this.data;
    clearInterval(timeTaskHandler)
    clearInterval(time)
  },
  // 用户分享
  onShareAppMessage: function () {
    let title = app.shareAppMessage().title;
    let imageUrl = app.shareAppMessage().imageUrl;
    let desc = app.shareAppMessage().desc;
    let path = app.shareAppMessage().path;
    console.log(app.shareAppMessage())
    return {
      title: title,
      imageUrl: imageUrl,
      desc: desc,
      path: path,
    }
  },
})